package com.bejoy.coolatin.volley;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.entity.StringEntity;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;

/**
 * 接口数据调用类
 * 
 * @author Savvy 2014.12.01
 */
public class InterfaceViaVolleys {

	private static final String TAG = "ValleyTest";
	private StringEntity mEntity = null;
	private Listener<String> mListener;
	private ErrorListener errorListener;
	private String encoding = "UTF-8";
	private String url = null;
	private Map<String, String> map = null;

	// public static CodeViaVolley instance = null;

	public InterfaceViaVolleys(Map<String, String> map, String url, String encoding,
			Listener<String> mListener, ErrorListener errorListener) {
		this.map = map;
		this.url = url;
		if (encoding != null) {// 编码默认为UTF-8
			this.encoding = encoding;
		}
		this.mListener = mListener;
		this.errorListener = errorListener;
	}

	/**
	 * 单利设计模式
	 * 
	 * @param context
	 *            上下文对象
	 * @param map
	 *            post方式成员，没有则为get方式
	 * @param url
	 *            网址
	 * @param code
	 *            编码
	 * @param mListener
	 *            成功回调函数
	 * @param errorListener
	 *            失败毁掉函数
	 * @return 实例化对象
	 */
	// public static CodeViaVolley getInstance(Map<String, String> map,
	// String url, String code, Listener<String> mListener,
	// ErrorListener errorListener) {
	// if (instance == null) {
	// instance = new CodeViaVolley(map, url, code, mListener,
	// errorListener);
	// }
	// return instance;
	// }

	public void stringRequest() {

		// String body = "";
		// try {
		// mEntity = new StringEntity(body);
		// } catch (UnsupportedEncodingException e1) {
		// e1.printStackTrace();
		// }

		if (errorListener == null) {
			errorListener = new Response.ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError arg0) {

				}
			};
		}
		// RequestQueue requestQueue = Volley.newRequestQueue(mContext);
		StringRequest request = null;
		if (this.map != null && this.map.size() > 0) {// post方式
			request = new StringRequest(Request.Method.POST, url, mListener,
					errorListener) {

				@Override
				protected Map<String, String> getParams()
						throws AuthFailureError {
					return InterfaceViaVolleys.this.map;
				}

				@Override
				protected Response<String> parseNetworkResponse(
						NetworkResponse response) {
					try {
						String jsonString = new String(response.data, encoding);
						return Response.success(jsonString,
								HttpHeaderParser.parseCacheHeaders(response));
					} catch (UnsupportedEncodingException e) {
						return Response.error(new ParseError(e));
					} catch (Exception je) {
						return Response.error(new ParseError(je));
					}
				}

				// 设置访问自己服务器时必须传递的参数，密钥等
				@Override
				public Map<String, String> getHeaders() throws AuthFailureError {
					HashMap<String, String> headers = new HashMap<String, String>();
					headers.put("key", "value");
					// headers.put("Accept", "application/json");
					// headers.put("Content-Type","application/x-www-form-urlencoded");
					return headers;
				}

				@Override
				public byte[] getPostBody() throws AuthFailureError {
					ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
					try {
						mEntity.writeTo(outputStream);
					} catch (IOException e) {
						Log.e(TAG, "IOException @ "
								+ getClass().getSimpleName());
					}
					return outputStream.toByteArray();
				}

				@Override
				public String getPostBodyContentType() {
					return mEntity.getContentType().getValue();
				}

			}// 重载的方法体
			;
		} else { // get方式
			request = new StringRequest(Request.Method.GET, url, mListener,
					errorListener) {

				@Override
				protected Response<String> parseNetworkResponse(
						NetworkResponse response) {
					try {
						String jsonString = new String(response.data, encoding);
						return Response.success(jsonString,
								HttpHeaderParser.parseCacheHeaders(response));
					} catch (UnsupportedEncodingException e) {
						return Response.error(new ParseError(e));
					} catch (Exception je) {
						return Response.error(new ParseError(je));
					}
				}

				@Override
				public Map<String, String> getHeaders() throws AuthFailureError {
					HashMap<String, String> headers = new HashMap<String, String>();
					headers.put("key", "value");
					return headers;
				}

				@Override
				public byte[] getPostBody() throws AuthFailureError {
					ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
					try {
						mEntity.writeTo(outputStream);
					} catch (IOException e) {
						Log.e(TAG, "IOException @ "
								+ getClass().getSimpleName());
					}
					return outputStream.toByteArray();
				}

				@Override
				public String getPostBodyContentType() {
					return mEntity.getContentType().getValue();
				}

			}// 重载的方法体
			;
		}

		RequestManagers.getRequestQueue().add(request);// 将请求加入到队列中
	}

}
